/**
 * 启动程序主文件 (Electron)
 * 用途：提供可视化界面启动后端和各个前端
 */

const { app, BrowserWindow, Menu, ipcMain, dialog } = require('electron');
const path = require('path');
const { spawn, exec } = require('child_process');
const fs = require('fs');
const os = require('os');

let mainWindow;
let processes = {};
const CONFIG_FILE = path.join(app.getAppPath(), 'config.json');

// 读取配置
function loadConfig() {
  try {
    if (fs.existsSync(CONFIG_FILE)) {
      return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
    }
  } catch (err) {
    console.error('读取配置文件失败:', err);
  }
  
  return {
    backend: {
      name: '后端服务',
      path: 'elmboot',
      command: 'mvn spring-boot:run',
      port: 8890
    },
    frontends: [
      {
        name: '用户端',
        path: 'elmclient',
        command: 'npm run serve',
        port: 8081
      },
      {
        name: '商家端',
        path: 'elmbusiness',
        command: 'npm run serve',
        port: 8082
      },
      {
        name: '管理端',
        path: 'elmadministrator',
        command: 'npm run serve',
        port: 8083
      }
    ]
  };
}

const config = loadConfig();

/**
 * 创建主窗口
 */
function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 700,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true
    },
    icon: path.join(__dirname, 'assets', 'icon.png')
  });

  mainWindow.loadFile(path.join(__dirname, 'index.html'));
  mainWindow.webContents.openDevTools();

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

/**
 * 启动服务
 */
ipcMain.handle('start-service', async (event, serviceName, serviceType) => {
  try {
    const service = serviceType === 'backend' 
      ? config.backend 
      : config.frontends.find(f => f.name === serviceName);

    if (!service) {
      throw new Error(`未找到服务: ${serviceName}`);
    }

    const projectPath = path.join(app.getAppPath(), '..', service.path);

    if (!fs.existsSync(projectPath)) {
      throw new Error(`项目路径不存在: ${projectPath}`);
    }

    // 检查是否已运行
    if (processes[serviceName]) {
      return { success: false, message: `${serviceName} 已在运行` };
    }

    // 启动进程
    const proc = spawn('cmd', ['/c', service.command], {
      cwd: projectPath,
      stdio: 'pipe',
      shell: true
    });

    processes[serviceName] = proc;

    // 监听输出
    proc.stdout?.on('data', (data) => {
      mainWindow?.webContents.send('service-output', {
        service: serviceName,
        output: data.toString(),
        type: 'stdout'
      });
    });

    proc.stderr?.on('data', (data) => {
      mainWindow?.webContents.send('service-output', {
        service: serviceName,
        output: data.toString(),
        type: 'stderr'
      });
    });

    proc.on('close', (code) => {
      delete processes[serviceName];
      mainWindow?.webContents.send('service-stopped', {
        service: serviceName,
        code
      });
    });

    return {
      success: true,
      message: `${serviceName} 启动成功`,
      port: service.port
    };
  } catch (err) {
    return {
      success: false,
      message: `启动失败: ${err.message}`
    };
  }
});

/**
 * 停止服务
 */
ipcMain.handle('stop-service', async (event, serviceName) => {
  try {
    const proc = processes[serviceName];
    if (!proc) {
      return { success: false, message: `${serviceName} 未运行` };
    }

    proc.kill();
    delete processes[serviceName];

    return {
      success: true,
      message: `${serviceName} 已停止`
    };
  } catch (err) {
    return {
      success: false,
      message: `停止失败: ${err.message}`
    };
  }
});

/**
 * 获取服务状态
 */
ipcMain.handle('get-services-status', async (event) => {
  const status = {
    backend: {
      name: config.backend.name,
      running: !!processes[config.backend.name],
      port: config.backend.port,
      url: `http://localhost:${config.backend.port}`
    },
    frontends: config.frontends.map(f => ({
      name: f.name,
      running: !!processes[f.name],
      port: f.port,
      url: `http://localhost:${f.port}`
    }))
  };
  return status;
});

/**
 * 打开浏览器
 */
ipcMain.handle('open-url', async (event, url) => {
  const { shell } = require('electron');
  await shell.openExternal(url);
});

/**
 * 获取配置信息
 */
ipcMain.handle('get-config', async (event) => {
  return config;
});

/**
 * 应用启动
 */
app.on('ready', createWindow);

app.on('window-all-closed', () => {
  // 停止所有进程
  Object.values(processes).forEach(proc => proc.kill());
  
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow();
  }
});

/**
 * 创建菜单
 */
app.on('ready', () => {
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '退出',
          accelerator: 'CmdOrCtrl+Q',
          click: () => app.quit()
        }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            dialog.showMessageBox(mainWindow, {
              type: 'info',
              title: '关于 ELM 启动器',
              message: 'ELM 项目启动管理工具',
              detail: '版本 1.0.0\n用于启动后端和各个前端服务'
            });
          }
        }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
});
